import threading
import time
import pandas as pd
import tablib as tb
import datetime as dt
import common.constants as const
from common.helper_hq_tushare import HQHelperTuShare
from common.helper_log import LogHelper as log

class HQFactory:
    """
        封装所有HQ相关操作，给外界提供统一接口
        底层封装用Tushare，或者其他数据源
    """
    def __init__(self):
            pass


    startDate:dt.datetime = None
    endDate:dt.datetime = None
    data:pd.DataFrame = None
    path = None
    tushareHelper = None

    def __init__(self, args=(), kwargs={}):
        super(HQFactory, self).__init__()
        self.tushareHelper = HQHelperTuShare()

    def get_kline_day_by_tradedate(self, code_list):
        """增量获取最近的K线数据
        但是想到，自己的标的量也不大，也就几个，暂时不用增量获取， 等以后有需要再说  V11
        """
        try:  
            return self.tushareHelper.get_kline_day_by_trade_date(code_list)
            # if exist:
            #     df = self.hqHelper.get_kline_day_by_code(code, start_date=start_date, end_date=end_date)
            # else:
            #     df = self.hqHelper.get_kline_day_by_trade_date(exchange=self.exchange, trade_date=start_date)

            # return df
        except Exception as e:
            msg = (f'【HQFactory_get_kline_day_by_tradedate】获取【{code_list}】K线数据失败:{e}')
            log.log_error(msg)
            
    def get_kline_day(self, code, start_date, end_date):
        """获取指定日期的K线数据"""
        try:
            df = self.tushareHelper.get_kline_day_by_code(code, start_date, end_date)
            
            return df
        except Exception as e:
            msg = (f'【HQFactory_get_kline_day】获取{code}K线数据失败:{e}')
            log.log_error(msg)

    def save_kline(self, df):
        """保存K线数据到本地文件， rawDate目录下"""
        self.tushareHelper.save(df, filename=f"DayKline_{df.Name}.csv")


    def save_progress(self, code, start_date, end_date):
        """保存进度:
         【获取日期】| 合约 |  开始时间 | 结束时间  |条数 |

        """
        df = pd.DataFrame({"getdate": [dt.datetime.now().strftime("%Y%m%d")],
                   'code': [code],
                   'startdate': [start_date],
                   'enddate': [end_date],
                   'gettime':[dt.datetime.now().strftime("%H:%M:%S")]})

        self.tushareHelper.save_progress(df)

    def get_progress(self, code):
        """保存进度:
         【获取日期】| 合约 |  开始时间 | 结束时间  |条数 |

        """
        df = self.tushareHelper.get_progress(code)

        df = df.sort_values(by='getdate', ascending=False)

        return df.iloc[0]
    